package com.wendy.job.controller;

import com.wendy.common.core.constant.Constants;
import com.wendy.common.core.domain.TableDataInfo;
import com.wendy.common.core.exception.job.TaskException;
import com.wendy.common.core.utils.StringUtils;
import com.wendy.common.log.annotation.Log;
import com.wendy.common.log.enums.BusinessType;
import com.wendy.common.web.controller.BaseController;
import com.wendy.custom.security.annotation.RequiresPermissions;
import com.wendy.custom.security.utils.SecurityUtils;
import com.wendy.excel.ruoyi.utils.ExcelUtil;
import com.wendy.job.domain.bo.SysJobBo;
import com.wendy.job.domain.vo.SysJobExcelVo;
import com.wendy.job.domain.vo.SysJobVo;
import com.wendy.job.entity.SysJob;
import com.wendy.job.errorcode.JobError;
import com.wendy.job.service.ISysJobService;
import com.wendy.job.util.CronUtils;
import com.wendy.job.util.ScheduleUtils;
import com.wendy.utils.spring.MapstructUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author wendy
 */
@RestController
@RequestMapping("/job")
public class SysJobController extends BaseController {
    @Autowired
    private ISysJobService jobService;

    /**
     * 查询定时任务列表
     */
    @RequiresPermissions("monitor:job:list")
    @GetMapping("/page")
    public TableDataInfo page(SysJobBo sysJob) {
        TableDataInfo<SysJobVo> list = jobService.selectJobPage(sysJob);
        return list;
    }

    /**
     * 导出定时任务列表
     */
    @RequiresPermissions("monitor:job:export")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJobBo sysJob) {
        List<SysJob> list = jobService.selectJobList(sysJob);
        ExcelUtil<SysJobExcelVo> util = new ExcelUtil<SysJobExcelVo>(SysJobExcelVo.class);
        util.exportExcel(response, MapstructUtils.convert(list, SysJobExcelVo.class), "定时任务");
    }

    /**
     * 获取定时任务详细信息
     */
    @RequiresPermissions("monitor:job:query")
    @GetMapping(value = "/{jobId}")
    public SysJobVo getInfo(@PathVariable("jobId") Long jobId) {
        return jobService.selectJobById(jobId);
    }

    /**
     * 新增定时任务
     */
    @RequiresPermissions("monitor:job:add")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping
    public int add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            JobError.ADD_CRON_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            JobError.ADD_RMI_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            JobError.ADD_LDAP_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            JobError.ADD_HTTP_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            JobError.ADD_CHAR_ERROR.formatFire(job.getJobName());
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            JobError.ADD_WHITE_ERROR.formatFire(job.getJobName());
        }
        job.setCreateBy(SecurityUtils.getUsername());
        return jobService.insertJob(job);
    }

    /**
     * 修改定时任务
     */
    @RequiresPermissions("monitor:job:edit")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public int edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            JobError.EDIT_CRON_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            JobError.EDIT_RMI_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            JobError.EDIT_LDAP_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            JobError.EDIT_HTTP_ERROR.formatFire(job.getJobName());
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            JobError.EDIT_CHAR_ERROR.formatFire(job.getJobName());
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            JobError.EDIT_WHITE_ERROR.formatFire(job.getJobName());
        }
        job.setUpdateBy(SecurityUtils.getUsername());
        return jobService.updateJob(job);
    }

    /**
     * 定时任务状态修改
     */
    @RequiresPermissions("monitor:job:changeStatus")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public int changeStatus(@RequestBody SysJobBo job) throws SchedulerException {
        SysJob jb = new SysJob();
        jb.setJobId(job.getJobId());
        jb.setStatus(jb.getStatus());
        return jobService.changeStatus(jb);
    }

    /**
     * 定时任务立即执行一次
     */
    @RequiresPermissions("monitor:job:changeStatus")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/run")
    public boolean run(@RequestBody SysJob job) throws SchedulerException {
        boolean result = jobService.run(job);
        if(!result){
            JobError.EDIT_EXPIRE_ERROR.fire();
        }
        return result ;
    }

    /**
     * 删除定时任务
     */
    @RequiresPermissions("monitor:job:remove")
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public boolean remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
        jobService.deleteJobByIds(jobIds);
        return true;
    }
}
